// import 'package:flutter/material.dart';
// import 'package:flutter_framework/utils/logs.dart';
//
// class SortColorBox extends StatefulWidget {
//   const SortColorBox({super.key});
//
//   @override
//   State<SortColorBox> createState() => _SortColorBoxState();
// }
//
// class _SortColorBoxState extends State<SortColorBox> {
//   final List<Color> _boxs = [
//     Colors.blue[100]!,
//     Colors.blue[300]!,
//     Colors.blue[600]!,
//     Colors.blue[700]!,
//     Colors.blue[800]!,
//     Colors.blue[900]!,
//   ];
//   int current = 0;
//
//   void shuffle() {
//     setState(() {
//       _boxs.shuffle();
//     });
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text('颜色排序盒子'),
//       ),
//       body: Column(
//         children: [
//           Container(
//             width: double.infinity,
//             height: 150,
//             margin: const EdgeInsets.only(top: 10, left: 10),
//             child: Stack(
//               children: List.generate(
//                   _boxs.length,
//                   (index) => ColorBox(
//                         color: _boxs[index],
//                         onDragUpdate: (event) {
//                           double dx = event.localPosition.dx;
//                           logs(
//                               'index:$current,dx:$dx,color box x:${(current + 1) * (ColorBox.width)}');
//                           if (dx > ((current + 1) * ColorBox.width)) {
//                             if (current == _boxs.length - 1) return;
//                             setState(() {
//                               final oldItem = _boxs[current];
//                               _boxs[current] = _boxs[current + 1];
//                               _boxs[current + 1] = oldItem;
//                               current++;
//                             });
//                           } else if (dx < (current * ColorBox.width)) {
//                             if (dx < 0) return;
//                             setState(() {
//                               final oldItem = _boxs[current];
//                               _boxs[current] = _boxs[current - 1];
//                               _boxs[current - 1] = oldItem;
//                               current--;
//                             });
//                           }
//                         },
//                         onDragStarted: () {
//                           logs(index);
//                           current = index;
//                         },
//                         x: ColorBox.width * index,
//                         key: ValueKey(_boxs[index]),
//                       )),
//             ),
//           )
//         ],
//       ),
//       floatingActionButton: FloatingActionButton(
//         onPressed: shuffle,
//         child: const Icon(
//           Icons.refresh,
//         ),
//       ),
//     );
//   }
// }
//
// class ColorBox extends StatelessWidget {
//   static const double width = 60.0;
//   static const double height = 100.0;
//   final Color color;
//   final double x;
//   final Function(DragUpdateDetails) onDragUpdate;
//   final void Function() onDragStarted;
//
//   ColorBox(
//       {super.key,
//       required this.color,
//       required this.x,
//       required this.onDragStarted,
//       required this.onDragUpdate});
//
//   late final Widget _container = Container(
//     width: width - 10,
//     height: height - 10,
//     decoration:
//         BoxDecoration(color: color, borderRadius: BorderRadius.circular(10)),
//   );
//
//   @override
//   Widget build(BuildContext context) {
//     return AnimatedPositioned(
//       duration: const Duration(milliseconds: 200),
//       left: x,
//       child: Draggable(
//           feedback: _container,
//           childWhenDragging: Visibility(
//             visible: false,
//             child: _container,
//           ),
//           onDragUpdate: onDragUpdate,
//           onDragStarted: onDragStarted,
//           child: _container),
//     );
//   }
// }
// 上面是横着排列 下面是竖着排列

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_framework/utils/logs.dart';

class SortColorBox extends StatefulWidget {
  const SortColorBox({super.key});

  @override
  State<SortColorBox> createState() => _SortColorBoxState();
}

class _SortColorBoxState extends State<SortColorBox> {
  final GlobalKey _stackKey = GlobalKey();
  List<Color> _boxs = [];
  int current = 0;
  late Color primaryColor;
  bool isSuccess = false;

  void shuffle() {
    genBox();
    setState(() {
      _boxs.shuffle();
      checkWin();
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    shuffle();
    super.initState();
  }

  void genBox() {
    var _color = Colors.primaries[Random().nextInt(Colors.primaries.length)];
    primaryColor = _color;
    _boxs = List.generate(7, (index) {
      return _color[(index + 1) * 100]!;
    });
  }

  void checkWin() {
    // 使用循环对比
    // bool success = true;
    // for (int i = 0; i < _boxs.length - 1; i++) {
    //   // 如果有一个比上一个小，则游戏失败
    //   if (_boxs[i].computeLuminance() > _boxs[i + 1].computeLuminance()) {
    //     print(
    //         "${_boxs[i].computeLuminance()},${_boxs[i + 1].computeLuminance()}");
    //     success = false;
    //     break;
    //   }
    // }
    // setState(() {
    //   isSuccess = success;
    // });
    // 直接使用排序对比 未完成，代码有问题
    List<double> _arr = _boxs.map((item) => item.computeLuminance()).toList();
    List<double> _copyArr = List.generate(_arr.length, (index) => _arr[index]);
    _arr.sort();
    // 相反的排序
    // _arr.sort();
    // _arr = _arr.reversed.toList();
    // print('数组1${_arr}');
    // print('数组2${_copyArr}');
    bool _success = true;
    setState(() {
      for (int i = 0; i < _arr.length; i++) {
        if (_arr[i] != _copyArr[i]) {
          _success = false;
          break;
        }
      }
      setState(() {
        isSuccess = _success;
      });
      // if ( == copyArr) {
      //   isSuccess = true;
      // } else {
      //   isSuccess = false;
      // }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('颜色排序盒子'),
        actions: [IconButton(onPressed: shuffle, icon: Icon(Icons.refresh))],
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('${isSuccess ? "胜利" : "未完成"}'),
            SizedBox(
              height: 20,
            ),
            Container(
              width: ColorBox.width - 10,
              height: ColorBox.height - 10,
              decoration: BoxDecoration(
                  color: primaryColor, borderRadius: BorderRadius.circular(10)),
              child: Icon(
                Icons.lock,
                color: Colors.white,
              ),
            ),
            Container(
              width: 200,
              height: 600,
              margin: const EdgeInsets.only(top: 10, left: 10),
              child: Stack(
                key: _stackKey,
                children: List.generate(
                    _boxs.length,
                    (index) => ColorBox(
                          color: _boxs[index],
                          onDragUpdate: (event) {
                            final RenderBox stackBox = _stackKey.currentContext
                                ?.findRenderObject() as RenderBox;
                            final _stackTop =
                                stackBox.localToGlobal(Offset.zero).dy;
                            // 获取当前距离顶部的 top 距离，不然算不准
                            double dy = event.localPosition.dy - _stackTop;
                            // logs(
                            //     'index:$current,dx:$dy,color box x:${(current + 1) * (ColorBox.height)}');
                            if (dy > ((current + 1) * ColorBox.height)) {
                              if (current == _boxs.length - 1) return;
                              setState(() {
                                final oldItem = _boxs[current];
                                _boxs[current] = _boxs[current + 1];
                                _boxs[current + 1] = oldItem;
                                current++;
                              });
                            } else if (dy < (current * ColorBox.height)) {
                              if (dy < 0) return;
                              setState(() {
                                final oldItem = _boxs[current];
                                _boxs[current] = _boxs[current - 1];
                                _boxs[current - 1] = oldItem;
                                current--;
                              });
                            }
                          },
                          onDragEnd: (_) {
                            checkWin();
                          },
                          onDragStarted: () {
                            logs(index);
                            current = index;
                          },
                          y: ColorBox.height * index,
                        )),
              ),
            )
          ],
        ),
      ),
      // floatingActionButton: FloatingActionButton(
      //   onPressed: shuffle,
      //   child: const Icon(
      //     Icons.refresh,
      //   ),
      // ),
    );
  }
}

class ColorBox extends StatelessWidget {
  static const double height = 60.0;
  static const double width = 200.0;
  final Color color;
  final double y;
  final Function(DragUpdateDetails) onDragUpdate;
  final void Function() onDragStarted;
  final void Function(DraggableDetails)? onDragEnd;

  ColorBox(
      {required this.color,
      required this.y,
      required this.onDragStarted,
      required this.onDragEnd,
      required this.onDragUpdate})
      : super(key: ValueKey(color));

  late final Widget _container = Container(
    width: width - 10,
    height: height - 10,
    decoration:
        BoxDecoration(color: color, borderRadius: BorderRadius.circular(10)),
  );

  @override
  Widget build(BuildContext context) {
    return AnimatedPositioned(
      duration: const Duration(milliseconds: 200),
      top: y,
      child: Draggable(
          feedback: _container,
          childWhenDragging: Visibility(
            visible: false,
            child: _container,
          ),
          onDragUpdate: onDragUpdate,
          onDragEnd: onDragEnd,
          onDragStarted: onDragStarted,
          child: _container),
    );
  }
}
